package com.javasm.adminapi.module.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javasm.adminapi.module.system.dao.RolePermissionDao;
import com.javasm.adminapi.module.system.dto.PerDTO;
import com.javasm.adminapi.module.system.dto.RolePermissionDTO;
import com.javasm.adminapi.module.system.entity.Permission;
import com.javasm.adminapi.module.system.entity.RolePermission;
import com.javasm.adminapi.module.system.service.RolePermissionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色权限中间表(RolePermission)表服务实现类
 *
 * @author makejava
 * @since 2025-10-18 22:29:09
 */
@Service("rolePermissionService")
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionDao, RolePermission> implements RolePermissionService {

    @Override
    public void deleteByPermissionIds(List<Long> collect2) {
        LambdaQueryWrapper<RolePermission> in = new LambdaQueryWrapper<RolePermission>()
                .in(RolePermission::getPermissionId, collect2);
        this.remove(in);
    }

    @Override
    public void updateByRid(RolePermissionDTO rolePermissionDTO) {
        Long rid = rolePermissionDTO.getRid();
        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermission::getRoleId,rid);
        this.remove(queryWrapper);
        List<Long> permissionIds = rolePermissionDTO.getPermissionIds();

        if(permissionIds!=null&&!permissionIds.isEmpty()){
            List<RolePermission> rolePermissions = permissionIds.stream()
                    .map(pid->{
                        RolePermission rolePermission = new RolePermission();
                        rolePermission.setRoleId(rid);
                        rolePermission.setPermissionId(pid);
                        return rolePermission;
                    }).collect(Collectors.toList());
            this.saveBatch(rolePermissions);
        }
    }

    @Resource
    RolePermissionDao rolePermissionDao;

    @Override
    public RolePermission getRolePermission(Long pid, Long rid) {

        RolePermission one = rolePermissionDao.getRolePermission(pid, rid);
        return one;
    }

    @Override
    public void savePerDTO(PerDTO permission) {
        List<Permission> permissions = permission.getPermissions();
        Integer roleId = permission.getRoleId();
        permissions.forEach(permission1 -> {
            RolePermission byId = rolePermissionDao.getByIdd(permission1.getMenuId(),roleId);
            byId.setAdd(permission1.getAdd());
            byId.setUpdate(permission1.getUpdate());
            byId.setDelete(permission1.getDelete());
            rolePermissionDao.updateByIdd(byId);
        });

    }


}
